package ch6;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "EditServlet",value = "/edit")
public class EditServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding ("utf-8");
UserBean user = new UserBean ();
String birthday = request.getParameter ("birthday");
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
        Date date =null;

            try {
                date =sdf.parse (birthday);
            } catch (ParseException e) {
                e.printStackTrace ();
            }
        user.setId (Integer.parseInt ("id"));
        user.setUserName (request.getParameter ("userName"));
        user.setUserCode (request.getParameter ("userCode"));
        user.setUserPassword (request.getParameter ("userPassword"));
        user.setGender (Integer.parseInt ("Gender"));
        user.setBirthday (date );
        user.setAddress (request.getParameter ("address"));
        user.setPhone (request.getParameter ("phone"));
        user.setUserRole (Integer.parseInt ("userRole"));
        UserDao userDao = new UserDao();
        int result =UserDao.updateUser(user);
        if (result > 0){
            System.out.println ("修改成功");
            response.sendRedirect ("main");
        }else {
            System.out.println ("修改失败");
            response.sendRedirect ("main");
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt (request.getParameter ("id"));
UserDao userDao = new UserDao ();
UserBean userBean= userDao.findById (id);
request.setAttribute ("user",userBean);
request.getRequestDispatcher ("/WEB-INF/editUser.jsp").forward (request,response);

    }
}
